%function CADX3_EXEC(varargin)

%-------------------------------------------------------------------------

%  This module opens the scratch files: IMPACT7.ASC and IMPACT10.ASC;
%  opens and reads the Head.ASC, loading the scroll variable arrays
%  and the plot variable arrays, then closes the file;  and provides the
%  control for the CADAC simulations under multi-run conditions.
%  Re-initializing the C variable from tape 90 is also performed in this
%  module.

%--Local Variable Definitions-------------------------------------------

% INITSUBS - (I) Flag: 0= Beginning of the trajectory - Execute the
%            initialization modules; 1= Middle of trajectory - Skip the
%            initialization modules.  Istage cannot be used for this
%            because it is modified by the input.
% NPLOTVAR - (I) The number of plot variables selected on the HEAD.ASC
%            file by the user.

%-------------------------------------------------------------------------

%---  Storage locations for exec are 50-99


%global unit2fid
%persistent der flag13 v ; 

%format_940=['0------ TOO MANY STATE VARIABLES. ','RUN ABORTED. ------'];
%nplotvar=[];n=[];icall=[];iunit=[];
%global bcom_1; if isempty(bcom_1), bcom_1=zeros(1,3510); end;
%% common           c(3510);
%% common           bcom_1(3510);

% common :: ;
%global ccom_1; if isempty(ccom_1), ccom_1=zeros(1,25); end;
%global ccom_2; if isempty(ccom_2), ccom_2=zeros(1,25); end;
%global ccom_3; if isempty(ccom_3), ccom_3=zeros(1,25); end;
%global ccom_4; if isempty(ccom_4), ccom_4=zeros(1,25); end;
%global ccom_5; if isempty(ccom_5), ccom_5=zeros(1,25); end;
%global ccom_6; if isempty(ccom_6), ccom_6=zeros(1,25); end;
%global ccom_7; if isempty(ccom_7), ccom_7=0; end;
%global ccom_8; if isempty(ccom_8), ccom_8=zeros(1,25); end;
%% common /ccom/    icf(25), icc(25), icl(25), ca(25),cl(25), ct0(25), nc, icl2(25);
%% common /ccom/    ccom_1(25), ccom_2(25), ccom_3(25), ccom_4(25),ccom_5(25), ccom_6(25), ccom_7, ccom_8(25);

% common :: ;
%global fileflg_1; if isempty(fileflg_1), fileflg_1=false; end;
%global fileflg_2; if isempty(fileflg_2), fileflg_2=false; end;
%global fileflg_3; if isempty(fileflg_3), fileflg_3=false; end;
%global fileflg_4; if isempty(fileflg_4), fileflg_4=false; end;
%global fileflg_5; if isempty(fileflg_5), fileflg_5=false; end;
%global fileflg_6; if isempty(fileflg_6), fileflg_6=false; end;
%global fileflg_7; if isempty(fileflg_7), fileflg_7=false; end;
%global fileflg_8; if isempty(fileflg_8), fileflg_8=false; end;
%global fileflg_9; if isempty(fileflg_9), fileflg_9=false; end;
%global fileflg_10; if isempty(fileflg_10), fileflg_10=false; end;
%% common /fileflg/trajbin, trajasc, statbin, statasc, tabout,ranvar,  initasc, initbin, trackasc, trackbin;
%% common /fileflg/fileflg_1, fileflg_2, fileflg_3, fileflg_4, fileflg_5,fileflg_6,  fileflg_7, fileflg_8, fileflg_9, fileflg_10;

% common :: ;
%global fileids_1; if isempty(fileids_1), fileids_1=0; end;
%global fileids_2; if isempty(fileids_2), fileids_2=0; end;
%global fileids_3; if isempty(fileids_3), fileids_3=0; end;
%global fileids_4; if isempty(fileids_4), fileids_4=0; end;
%global fileids_5; if isempty(fileids_5), fileids_5=0; end;
%global fileids_6; if isempty(fileids_6), fileids_6=0; end;
%global fileids_7; if isempty(fileids_7), fileids_7=0; end;
%global fileids_8; if isempty(fileids_8), fileids_8=0; end;
%global fileids_9; if isempty(fileids_9), fileids_9=0; end;
%global fileids_10; if isempty(fileids_10), fileids_10=0; end;
%global fileids_11; if isempty(fileids_11), fileids_11=0; end;
%global fileids_12; if isempty(fileids_12), fileids_12=0; end;
%global fileids_13; if isempty(fileids_13), fileids_13=0; end;
%global fileids_14; if isempty(fileids_14), fileids_14=0; end;
%global fileids_15; if isempty(fileids_15), fileids_15=0; end;
%global fileids_16; if isempty(fileids_16), fileids_16=0; end;
%% common /fileids/ id_cadin,   id_head,    id_csave,   id_tabout,id_trajbin, id_trajasc, id_statbin, id_statasc,id_ranvar,  id_impact,  id_impact7, id_impact10,id_initasc, id_initbin, id_trackasc, id_trackbin;
%% common /fileids/ fileids_1,   fileids_2,    fileids_3,   fileids_4,fileids_5, fileids_6, fileids_7, fileids_8,fileids_9,  fileids_10,  fileids_11, fileids_12,fileids_13, fileids_14, fileids_15, fileids_16;

% common :: ;
%global firsti_1; if isempty(firsti_1), firsti_1=false; end;
%% common /firsti/ finit;
%% common /firsti/ firsti_1;

% common :: ;
%global flag1_1; if isempty(flag1_1), flag1_1=false; end;
%% common /flag1/   initgauss;
%% common /flag1/   flag1_1;

% common :: ;
%global krun_1; if isempty(krun_1), krun_1=0; end;
%global krun_2; if isempty(krun_2), krun_2=0; end;
%global krun_3; if isempty(krun_3), krun_3=0; end;
%% common /krun/    jrun, mulrun, igroup;
%% common /krun/    krun_1, krun_2, krun_3;

% common :: ;
%global nad_1; if isempty(nad_1), nad_1=0; end;
%global nad_2; if isempty(nad_2), nad_2=0; end;
%global nad_3; if isempty(nad_3), nad_3=0; end;
%global nad_4; if isempty(nad_4), nad_4=0; end;
%% common /nad/     ibeen, ibegin, icard, isave;
%% common /nad/     nad_1, nad_2, nad_3, nad_4;

% common :: ;
%global oindat_1; if isempty(oindat_1), oindat_1=0; end;
%global oindat_2; if isempty(oindat_2), oindat_2=0; end;
%global oindat_3; if isempty(oindat_3), oindat_3=0; end;
%% common /oindat/  j16, icd, i16;
%% common /oindat/  oindat_1, oindat_2, oindat_3;

% common :: ;
%global opflag_1; if isempty(opflag_1), opflag_1=false; end;
%global opflag_2; if isempty(opflag_2), opflag_2=false; end;
%global opflag_3; if isempty(opflag_3), opflag_3=false; end;
%global opflag_4; if isempty(opflag_4), opflag_4=false; end;
%% common /opflag/ intmsg, stgmsgout, inecho, xsweep;
%% common /opflag/ opflag_1, opflag_2, opflag_3, opflag_4;

% common :: ;
%global prev_1; if isempty(prev_1), prev_1=0; end;
%global prev_2; if isempty(prev_2), prev_2=0; end;
%global prev_3; if isempty(prev_3), prev_3=0; end;
%% common /prev/    tprev, cpprev, ppprev;
%% common /prev/    prev_1, prev_2, prev_3;

% common :: ;
%global stage1_1; if isempty(stage1_1), stage1_1=0; end;
%global stage1_2; if isempty(stage1_2), stage1_2=0; end;
%% common /stage1/  istage, numstage;
%% common /stage1/  stage1_1, stage1_2;

% common :: ;
%global stagec_1; if isempty(stagec_1), stagec_1=zeros(1,2); end;
%global stagec_2; if isempty(stagec_2), stagec_2=cell(1,2); end;
%% common /stagec/  name1(2), name2(2);
%% common /stagec/  stagec_1(2), stagec_2(2);

%if isempty(der), der=zeros(1,101); end;
%if isempty(v), v=zeros(1,101); end;


% equivalence(bcom_1(1801), critno  ) ::;
% equivalence(bcom_1(1802), critval ) ::;
% equivalence(bcom_1(2000), time    ) ::;
% equivalence(bcom_1(2006), itap90  ) ::;
% equivalence(bcom_1(2662), hmin    ) ::;
% equivalence(bcom_1(2663), hmax    ) ::;
% equivalence(bcom_1(2664), der(1)  ) ::;
% equivalence(bcom_1(2561), nip     ) ::;
% equivalence(bcom_1(2765), v(1)    ) ::;
% equivalence(bcom_1(2011), kstep   ) ::;
% equivalence(bcom_1(2285), nj      ) ::;
% equivalence(bcom_1(2280), nv      ) ::;
% equivalence(bcom_1(2001), tstage  ) ::;
% equivalence(bcom_1(2016), pgcnt   ) ::;
% equivalence(bcom_1(2020), lconv   ) ::;
% equivalence(bcom_1(2866), icoor   ) ::;


%      CHARACTER FILENAME*50
%      INTEGER GETENVQQ
%if isempty(flag13), flag13=false; end;

%      DATA C/ 3510 * 0.0 /



%---  Open and process the Head.ASC file information.
%[ nplotvar ]=rdh1_headr( nplotvar );


%---  Open the output files and start the tabular output by writing the
%---  title, variable headings, etc.
%[ nplotvar ]=op_start( nplotvar );


%---  Read the input card and load the card data into the modules
%rdi1_init_cards;



% 520 continue;


%---  Perform a write to the RANVAR output file (if it is requested)
%     to assist in finding variables assignments used in multi-run
%     cases

%if( fileflg_6 )
%writef(fileids_9,['%s %0.15g %s %0.15g '], ' IGROUP = ', krun_3, '  JRUN = ', krun_1);
%end;

%---  Very beginning of a trajectory calculation.
%     This section is the initialization of both Local and  EXEC common
%     variables.

flag1_1 = false;

ccom_7       = 0;
% Stage counter.
stage1_2 = 0;
% Flag: pull data from main trajectory arrays.
oindat_1      = 0;
% Main trajectory card counter.
oindat_2      = 0;
stage1_1   = 0;
initsubs = 0;
tstage   = 0.0;
prev_1    = 0.0;

%---  Initialize the C array to zeros:

%set_c_zero;

%global C;

C = zeros(1,3510);

%---  Setup a default critical value and variable for the non-sweep
%---  runs.   The input deck for sweep runs will reset these variables
%---  to the proper values.  The default variable for the non-sweep
%--   cases is DHJ = 1773.

critno = 1773;
critval = 0.00001;

%     Initialize the max and min plot variable arrays.

%ini1_pmin;

%---  Re- Initialize the common location that contains the number of
%---  variables in the plot list since this value has been zero-ed out
%---  by the above loop.
%nv = nplotvar;

%     Initialize the flag which indicates the action of the EXEC after
%     each integration loop.

kstep   = 1;

%     Initialize several earth and conversion variables.

ini1_vars;




% 580 continue;

%---  This section is where the input cards are processed.  The program
%     executes here at the beginning of each trajectory, and returns
%     here at the end of each stage to process the next set of stage cards.


if( lconv <= 0  )

%         The trajectory has not reached termination as defined by G4
%         module.

%         Perform the input card processing.

oinpt1;

if( hmin == 0.0 )
    hmin = der(1);
end;
if( hmax == 0.0 )
    hmax = der(1);
end;

if( initsubs == 0 )

%             This is the start of the trajectory computations.
%             At this point in the code, the variables have been
%             initialized and the stage 0 cards have been read
%             and processed.

%             IF( XSWEEP .AND. MULRUN .EQ. 0 ) THEN

%                 A Sweep case is being executed (Not with the multi-run
%                 mode : type 5 card)  Increment the run counter
%                 here (instead of in the type 21 card processing
%                 module {prior XR92} ) to keep the count of the number
%                 of executed trajectories correct.

%                  JRUN = JRUN + 1
%              ENDIF

go to 800;

else;

%             In the middle of a trajectory either through a stage
%             or a type 90 card.  Insure some values of the Executive
%             common/control variables.

lconv = 0;
kstep = 1;
pgcnt = 1;

intest = nv - 1;
noplot = min( 70, max( 0, intest) );
if( noplot > 0 )
ppcnt = time - 0.000001;
end;

%             Continue with integration cycle.

go to 880;
end;

else;

%         The end of the trajectory has occurred.
%         Read the input until an input card type 6 is found.

while( stage1_1 ~= 6 );
oinpt2;
end;

go to 1060;

end;




% 800 continue;

%     This section performs module initialization.

%---  Execute the pre-initialization modules for the type 1 card
%     modules.  NOTE:  Currently no modules defined in this module

subl1;


%---  Call the initialization modules for the type 2 card modules.

icoor = -2;

auxi;


%     Set the flag indicating that the initialization modules have been
%     executed for this trajectory.

initsubs = 1;


%---  Execute the initialization modules for the type 1 cards:
%     Call the initialization modules for the modules specified on the
%     input type 1 cards ( OUPT2 and STGE2 )

subl2;


%---  Load the V and DER variables from the C array:
%     Calculate the number if integration variables defined.

n  = max( 2, nip );

[ n ]=ld_deriv( n );

% 880 continue;

%     This section controls the execution of the modules and the
%     integration cycle.

%---  Execute the auxillary modules (type 2 card modules )

icoor = -1;

%     Call the modules specified on the type 2 cards.

auxsub;

if( firsti_1 )

%     Call the RT initialization routine if a RT INIT file is to be
%     created

op3_rtiwrite;
op3_rtwrite;
firsti_1 = false;

end;

%     Check for stage conditions being met.
%     This call statement was removed so that a redundant call to the stage
%     test routine was not called.  The stage routine is called after each
%     integration cycle is complete.  This call was made immediately after
%     group cards were loaded or after a previous stage [BC 8 Sep 98]
%BC      ICALL = 1
%BC      CALL STGE3( ICALL )


if( nip > 100 )

[writeErrFlag]=writeFmt(fileids_4,[format_940]);
%         Read the input until an input card type 6 is found.

while( stage1_1 ~= 6 );
oinpt2;
end;

go to 1060;
end;



% 960 continue;


%---  Execute the integration modules.

n = max( 2, nip );
n = min( n, 100 );

% Used in AMRK module
nj = n - 1;

amrk;


%---  Shift the data produced by the integration arrays into the C arrays.

[ n ]=ld_carray( n );


%---  Execute the card type 1 modules.

subl3;


%---  Check the status of the integration cycle:

if( kstep == 1 )

%         No change in status - Continue the integration cycle.

go to 960;

%zzzz
elseif( kstep == 2 ) ;

%         End of trajectory detected - Read the input until an input
%         card type 6 is found (incase not already at a type 6 card)

while( stage1_1 ~= 6 );
oinpt2;
end;

%---  Call STGE3 to write data to SWEEP files at end of total miss trajectory

if( lconv == 5 )
icall = 1;
[ icall ]=stge3( icall );
end;

elseif( kstep == 3 ) ;

%         The current stage requirements have been met.

go to 580;

end;




% 1060 continue;

%---  This section controls execution when the end of the trajector has
%---  been detected.


%---  Reset control flags
kstep = 1;
lconv = 0;
prev_1 = 0.0;

%---  Zero the integration array.
for jv = 2: n;
v(jv) = 0.0;
end; jv = n+1;


%---  Check for special execution cases:


if( opflag_4 )

%---       A sweep case is being executed and a trajectory has
%---       completed.

%---       Write the final trajectory data to the TRAJ.* file: ie the
%---       -1.0 record and the max data record.
if( fileflg_1 )
iunit = fileids_5;
[ iunit ]=op3_pf11( iunit );
end;
if( fileflg_2 )
iunit = fileids_6;
[ iunit ]=op3_pf11( iunit );
end;


if( krun_2 > 0   &&  krun_1 >= krun_2 )

%---           Finished all trajectory runs in the current sweep
%---           position (angle and range setting).  Reset the run
%---           counter and increment the group counter.
krun_1   = 0;
krun_3 = fix(krun_3 + 1);
end;

%---       Copy the primary, stored trajectory into the working arrays
%---       and run the next trajectory sweep.   The card type 18 causes
%---       the adjustments in the trajectory.
work;

%---       Restart for the next trajectory.  Branch to initialization.
krun_1 = fix(krun_1 + 1);
go to 520;

end;


%---  Write the final trajectory data to the trajectory file: ie the
%---  -1.0 record and the max data record.
if( fileflg_1 )
iunit = fileids_5;
[ iunit ]=op3_pf11( iunit );
end;
if( fileflg_2 )
iunit = fileids_6;
[ iunit ]=op3_pf11( iunit );
end;


if( krun_2 > 0 )

%---      Multi-run trajectory case:
%---      If the run counter is less than the maximum number of runs
%---      to be perform, then increment run counter and go perform another
%---      trajectory run.  Branch to the trajectory initialization.
if( krun_1 < krun_2 )
krun_1 = fix(krun_1 + 1);
go to 520;
end;

%---      Else - Finished all runs in the multi-run case.  Reset the run
%---      counter.  Reset the read from CSAVE.ASC file to indicate start
%---      of new group trajectory

krun_1   = 1;
nad_4 = 0;

end;

%---  Trajector(y/ies) for this base card set completed.  Continue
%---  reading the file to determine if group cards exist, and if so, process
%---  these trajectories.

%---  Increment the group counter.
krun_3 = fix(krun_3 + 1);

%---  Copy the primary trajectory to the working arrays,
%---  read the lead card deck for the cards in the next group and
%---  modifies/add them to the primary trajectory accordingly.
[ flag13 ]=rdi2_group( flag13 );

%---  If a card type 13 has not been read (or abnormal end of file
%---  reached), then a type 12 card at the end of a group card set
%---  was detected.  Go compute this trajectory.
if( ~ flag13  )
go to 520;
end;


%---  A type 13 card was encountered in the input stream.
%     End of simulation:  write the ending records to the trajectory file
%---  and statistics files. Then close the files.
%---  NOTE: Since converted from MS PowerStation 4.0 to Digital Visual FORTRAN
%           the ENDFILE statement was replaced with the CLOSE statement to
%           correctly disassociate the unit ID from the file without errors
%           for binary files. (The error was produced b/bcom_1 the file was not opened
%           as a sequential file ?)   [BC 26 May 98]

if( fileflg_3 )
iunit = fileids_7;
[ iunit ]=op3_pf11( iunit );
fclose(unit2fid(find(unit2fid(:,1)==fileids_7,1,'last'),2));
end;
if( fileflg_4 )
iunit = fileids_8;
[ iunit ]=op3_pf11( iunit );
fclose(unit2fid(find(unit2fid(:,1)==fileids_8,1,'last'),2));
end;

%---  The end records have already been recorded to the trajectory file.
fclose(unit2fid(find(unit2fid(:,1)==fileids_5,1,'last'),2));
fclose(unit2fid(find(unit2fid(:,1)==fileids_6,1,'last'),2));
fclose(unit2fid(find(unit2fid(:,1)==fileids_16,1,'last'),2));
fclose(unit2fid(find(unit2fid(:,1)==fileids_15,1,'last'),2));

error(['stop encountered in original fortran code  ',char(10),';']);





